package com.openxt.nbzj.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.openxt.nbzj.activity.JWGWDetailsActivity;
import com.openxt.nbzj.activity.NoticeDetailsActivity;
import com.openxt.nbzj.call.AccessStatisticsManager;
import com.openxt.nbzj.call.HeartBeatManager;
import com.openxt.nbzj.event.Event;
import com.openxt.nbzj.event.EventManager;
import com.openxt.nbzj.event.IEventHandler;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.PermissionsDispatcher;
import com.openxt.nbzj.push.Push;
import com.openxt.nbzj.remoting.ClientEx;

import com.alibaba.fastjson.JSONObject;

import permissions.dispatcher.PermissionRequest;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;
import qs.openxt.libs.view.UIAlertView;

/**
 * Created by 颖杰_2 on 2016/5/17.
 */
public class OpenxtBaseActivity extends AppCompatActivity implements IEventHandler {
    public OpenxtBaseStyle baseStyle;
    private String actionUrl = null;
    private Handler mHandler = new Handler();
    private Context mContext = null;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        mContext = this;

        qs.openxt.libs.App.PATH_NAME = getPackageName();

        OpenxtBaseManager.getInstance().addActivity(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                d();
            }
        }, 320);
    }

    private void d() {
        PermissionsDispatcher.initPermissionsDispatcher(this);
    }

    public void setActionUrl(String actionUrl){
        this.actionUrl = actionUrl;
    }

    public String getActionUrl(){
        return actionUrl;
    }

    /**
     * 设置页面资源
     * @param viewId
     * @param title
     * @return
     */
    public OpenxtBaseStyle setBaseStyle(int viewId, String title) {
        baseStyle = new OpenxtBaseStyle(this, viewId, title);
        return baseStyle;
    }

    /**
     * 设置页面头部文字
     * @param title
     * @return
     */
    public void setTitle(String title) {
        baseStyle.setTitle(title);
    }


    /**
     * 设置回退按钮是否显示
     * @param has
     */
    public void setBackBtn(boolean has){
        baseStyle.setBackBtn(has);
    }

    /**
     * 获取头部右边部分
     * @return
     */
    public LinearLayout getRight(){
        return baseStyle.getRight();
    }

    /**
     * 设置回退按钮事件
     * @param listener
     */
    public void setBackAction(OpenxtBaseStyle.OnBackActionListener listener) {
        baseStyle.setBackAction(listener);
    }

    public void toActivity(final Class<?> cls) {
        toActivity(cls, false);
    }

    public void toActivity(final Class<?> cls, final boolean closeFlag) {
        try {
            final Context mContext = this;
            Intent intent = new Intent();
            intent.setClass(mContext, cls);
            startActivity(intent);
            if (closeFlag)
                finish();
        } catch (Exception e) {

        }
    }

    public void toActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        try {
            Intent intent = new Intent();
            intent.setClass(this, cls);
            if (bundle != null)
                intent.putExtras(bundle);
            startActivityForResult(intent, requestCode);
        } catch (Exception e) {

        }
    }

    public void toActivity(final Class<?> cls, final Bundle bundle, final boolean closeFlag) {
        try {
            final Context mContext = this;
            Intent intent = new Intent();
            intent.setClass(mContext, cls);
            if (bundle != null)
                intent.putExtras(bundle);
            startActivity(intent);
            if (closeFlag)
                finish();
        } catch (Exception e) {

        }
    }

    public void toActivity(final Class<?> cls, final Bundle bundle) {
        toActivity(cls, bundle, false);
    }

    public void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            /**
             * 点击空白位置 隐藏软键盘
             */
            hideInputMethod();
        }
        return super.onTouchEvent(event);
    }

    public void showInputMethod(View view) {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }catch (Exception e){

        }
    }
    public void hideInputMethod(){
        try {
            View view = getCurrentFocus();
            if(view == null)
                return;
            IBinder iBinder = view.getWindowToken();
            if (iBinder == null)
                return;
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }catch (Exception e){

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        OpenxtBaseManager.getInstance().removeActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        EventManager.instance().addEventHandler(Push.PUSH_NOTIFIY_KEY, this);
        EventManager.instance().addEventHandler(ConfigModel.APP_NOTIFIY_KICKOUT, this);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                AccessStatisticsManager.instance().start(mContext, actionUrl, true);
            }
        }, 300);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventManager.instance().removeEventHandler(Push.PUSH_NOTIFIY_KEY, this);
        EventManager.instance().removeEventHandler(ConfigModel.APP_NOTIFIY_KICKOUT, this);
    }

    @Override
    public void handleEvent(Event event) throws Exception {
        if(Push.PUSH_NOTIFIY_KEY.equals(event.getType())) {
            JSONObject item = (JSONObject) event.getArg();
            if (item == null)
                return;
            JSONObject key1 = null;
            try {
                key1 = item.getJSONObject("key1");
            }catch (Exception e){
                key1 = JSON.parseObject(item.getString("key1"));
            }
            if(key1 == null)
                return;
            String id = key1.getString("id");
            if (StringUtil.isNull(id))
                return;
            String type = key1.getString("type");
            Utils.setLocalStorage(this, ConfigModel.NATIVE_PAGENAME, this.actionUrl);
            Bundle bundle = new Bundle();
            bundle.putString("ID", id);
            if("NOTICE".equals(type)) {
                toActivity(NoticeDetailsActivity.class, bundle, false);
            }else if("JWGW".equals(type)) {
                toActivity(JWGWDetailsActivity.class, bundle, false);
            }
        }else if(ConfigModel.APP_NOTIFIY_KICKOUT.equals(event.getType())){
            ClientEx.CUSTOMERID = null;
            Utils.removeLocalStorage(this, ClientEx.CUSTOMERID_KEY);
            Utils.removeLocalStorage(this, ConfigModel.LOGIN_NATIVE);
            HeartBeatManager.instance().stop();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    final UIAlertView dialog = new UIAlertView.Builder(mContext)
                            .setTitle("温馨提示")
                            .setMessage("您被强制下线，如有疑问，请联系住建委！")
                            .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    OpenxtBaseManager.getInstance().exit();
                                }
                            }).create();
                    dialog.setCancelable(false);
                    dialog.show();
                }
            }, 10);
        }
    }

    /*******权限********/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
